package json;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JavaJson {
    public static void main(String[] args) {
        Gson gson = new Gson();


        Book book = new Book(100, "韩顺平零基础学Java");
//      1.把javebean -> json字符串
        String strBook = gson.toJson(book);
        System.out.println("strBook=" + strBook);
//      2.json字符串->javabean
        Book book2 = gson.fromJson(strBook, Book.class);
        System.out.println("book2=" + book2);

//       3.演示把list对象 -> json字符串
        ArrayList<Book> bookList = new ArrayList<>();
        bookList.add(new Book(200, "天龙八部"));
        bookList.add(new Book(300, "三国演义"));
        String strBookList = gson.toJson(bookList);
        System.out.println("strBookList= " + strBookList);

//       4.把json字符串 -> list对象
        Type type = new TypeToken<>() {
        }.getType();
        List<Book> bookList2 = gson.fromJson(strBookList, type);
        System.out.println("bookList2= " + bookList2);

//      5, 把map对象->json字符串
        Map<String, Book> bookMap = new HashMap<>();
        bookMap.put("k1", new Book(400, "射雕英雄传"));
        bookMap.put("k2", new Book(500, "西游记"));
        String strBookMap = gson.toJson(bookMap);
        System.out.println("strBookMap=" + strBookMap);

//        6.把json字符串 -> map对象
        Type type1 = new TypeToken<Map<String, Book>>() {
        }.getType();
        Map<String, Book> bookMap2 = gson.fromJson(strBookMap, type1);
        System.out.println("bookMap2=" + bookMap2);
    }
}
